import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { App } from 'ionic-angular';
import { AccountDataService } from '../../providers/service/account-data.service';
import { Network } from '@ionic-native/network';

/**
 * Generated class for the AccountPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-account',
  templateUrl: 'account.html',
})
export class AccountPage {


  

  // 用户信息
  userInfo: login_info = new login_info();
  
  dictionary: Dictionary[] = new Array<Dictionary>();

  D_GROUP = 'REFUND_STATE';

  //页数
 page = 1;
 //有网状态=1 断网=0
 Internet = 1;
 // 下拉是否还有数据
  nodata = 0;

  //  这是全局变量账户明细
  public detailedInfo : detailedInfo[] =new Array<detailedInfo>();
    


  constructor(
    public navCtrl: NavController,
    public viewCtrl: ViewController,
    public navParams: NavParams,
    public http: HttpProvider,
    public storage: StorageProvider,
    public dialog: DialogProvider,
    public user: UserInfoProvider,
    public accountdata: AccountDataService,
    private network: Network,
    private app:App) { }

  async ionViewDidLoad() {
    console.log('ionViewDidLoad AccountPage');
    if (this.network.type!=='none' && this.network.type !== '2g') {
      this.Internet = 1;
      this.getAccount();
			return;
		}
		if (this.network.type === 'none' || this.network.type === '2g') {
			this.Internet = 0;
			let a = await this.accountdata.find((detailedInfo) => detailedInfo.key !== '');
			this.detailedInfo = a;
			return;
		}
    // this.storage.getStorage("login_info").then(res => {
    //   console.log('res');
    //   console.log(res);
    //   if(res != undefined) {
    //     this.balance=res['balance']
    //     this.local_balance=res['local_balance']
    //     this.member_id=res['member_id']
    //     this.getAccount();
    //   }
    // });

  }
  skipToChargingForAccount() {
    this.navCtrl.push("ChargingAccountPage");
  }

  //转入本地金额
  async turnMoney() {


    const a = await this.dialog.showPrompt('本地余额'+this.user.userInfo.local_balance+'元', '本地余额最多可存30元', [{ name: 'moneys', placeholder: '请输入转入金额', type: 'number' }]);
    if (a['code'] == "") {
      return;
    }
    //非空校验
     if (!a['data']['moneys'] || a['data']['moneys'] <= 0) {
      //  console.log(a);
      this.dialog.showAlert("转入的金额不正确", "");
      return;
    }
    /*
    if (a['data']['moneys'] == "" || a['data']['moneys'] == null) {
      //  console.log(a);
      this.dialog.showAlert("转入的金额为空", "");
      return;
    }
    if (a['data']['moneys'] == 0) {
      this.dialog.showAlert("转入金额为0", "");
      return;
    }
    */
    //正则表达式判断数字 要求只能为数字,如果有小数位,最多只能是2位小数
    var subscriber = /^\d+(?:\.\d{1,1})?$/;
    ///^[0-9]+([.]{1}[0-9]+){0,1}$/
    var stuip = subscriber.test(a['data']['moneys']);
    //是否是数字校验
    if (!stuip) {
      this.dialog.showAlert("转入的金额非法", "");
      return;
    }
    if (parseFloat(this.user.userInfo.balance) < a['data']['moneys']) {
      this.dialog.showAlert("转入金额大于账户余额", "");
      return;
    }
    if (parseFloat(this.user.userInfo.local_balance)==30) {
      this.dialog.showAlert("本地余额最大存储为30元", "");
      return;
    }

    var aa = parseFloat(this.user.userInfo.balance);
    var bb = parseFloat(this.user.userInfo.local_balance);
    const b = {
      old_balance: this.user.userInfo.balance,
      old_local_balance: this.user.userInfo.local_balance,
      balance: aa - parseFloat(a['data']['moneys']),
      local_balance: bb + parseFloat(a['data']['moneys']),
    }
    if (b.local_balance >30) {
      this.dialog.showAlert("本地余额最大存储为30元", "");
      return;
    }
    this.http.postJson('', 'member/member/update?id=' + this.user.userInfo.member_id, {
      "old_balance": b.old_balance,//原账户余额
      "old_local_balance": b.old_local_balance,//原本地余额
      "balance": b.balance.toString(),  //转了之后的余额
      "local_balance": b.local_balance.toString(),  //转了之后的本地余额
      "transfer_amount": a['data']['moneys']//转入金额
    }, '').then(res => {
      if (res['status'] == 200) {
        this.dialog.showAlert(res["message"],'');
        this.login().then( res => {this.navCtrl.setRoot('CenterPage')} );
		    
      }
    });
  }

  async login() {
    await this.storage.getStorage("login_info").then(res => {
      if (res != undefined) {
        this.userInfo = res;
      }
    });
    const res = await this.http.postJson('', 'member/member/view?id=' + this.user.userInfo.member_id, {}, '')
      .then(res => {
        if (res['status'] == 200) {
          res['data']['password'] = this.user.userInfo.password;
          res['data']['isAutomaticLogon'] = this.user.userInfo.isAutomaticLogon;
          this.userInfo = res['data'];
          this.user.setuserInfo(this.userInfo);
          // this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
          // this.navCtrl.push('CenterPage');
        }
      });
    return ;
  }
 


  //账户明细
  getAccount() {
    var params = {
      member_id: this.user.userInfo.member_id
    };
    this.http.postJson('', 'member/member/accountamount', {
      "member_id": params.member_id,
      "page": 1,
      "limit": "8",
      "balance":4,
      'orderBy': "created_at desc"
    }, '').then(res => {
      if (res['status'] == 200) {
        this.getMessage(res['data']);
        this.accountdata.save(this.detailedInfo);
//      this.nodata = 0;
      }
      if(res['data'].length < 8){
    	this.nodata = 1;
      }
      if(res['data'].length === 8){
    	this.nodata = 0;
      }
    });
  }

  async getMessage(detailedInfo) {
    this.detailedInfo.splice(0);
    for (let account of detailedInfo) {
      if (account) {
        var a = {
          moneys: account.moneys,
          created_at: account.created_at * 1000,
          tables: account.tables
        }
        await this.detailedInfo.push(a);
      }
    }
    this.accountdata.deleteAll();
		for (var i = 0; i < this.detailedInfo.length; i++) {
			this.accountdata.save(this.detailedInfo[i]);
		}
   
  }

  getdictionary() {
    this.dictionary = this.storage.getStorage('dictionary');
  }

  finddictionary(data) {
    for (let a of this.dictionary) {
      if (a.D_GROUP = this.D_GROUP) {
        for (let b of a.group) {
          b.D_VALUE = data;
          return b.D_NAME_CN;
        }
      }
    }
  }

  getTables(data) {
    if (data == 1) {
      return '退款';
    }
    if (data == 2) {
      return '充值';
    }
    if (data == 3) {
      return '转出';
    }
    if (data == 4) {
      return '消费';
    }

  }

   //无限滚动(下滑加载)
	 async  lodeMessage(infiniteScroll, type) {
    this.page++;
    const res = await this.http.postJson('', 'member/member/accountamount',
      {
        "member_id": this.user.userInfo.member_id,
        "page": this.page,
        "limit": "8",
        "balance":4,
        'orderBy': "created_at desc"
      }, '').then(res => {
        if (res['status'] == 200) {
        	
          if (res['data'].length === 0) {
				this.nodata = 1;
		  }
          	
          for (let account of res['data']) {
            if (account) {
              var a = {
                moneys: account.moneys,
                created_at: account.created_at * 1000,
                tables: account.tables
              }
               this.detailedInfo.push(a);
            }
          }
          if (type === 'scroll') {
				setInterval(infiniteScroll.complete(), 500);
		  }
        }
      });
  }

}


export class Dictionary {
  D_GROUP: any;
  group: any[];
}

export class detailedInfo {
  moneys: any;
  created_at: any;
  tables: any;
}

export class login_info {
  member_id: any;
  nickname: any;
  phone: any;
  balance: any;
  local_balance: any;
  member_state: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  is_del: any;
  password: any;
  file_type_id: any;
  access_token: any;
  isAutomaticLogon: any;
}